<?php

namespace Patrol\Controller;

use Think\Controller;

class ScanQRCodeController extends Controller {

    public function index($securityData) {
        $token = \Tool\Token::getToken($securityData->token);
        //
        
        $qrcode = \Tool\Qrcode::deqrcode($securityData->deviceId);
        if (empty($qrcode)) {
            echo json_encode(array('result' => false, 'message' => '不是我们的二维码！'));
            exit;
        }
        if (isset($qrcode->equ_id) && empty($qrcode->equ_id)) {
            echo json_encode(array('result' => false, 'message' => '不是我们的二维码！'));
            exit;
        }
//        if ($qrcode->useraccount != $token) {
//            echo json_encode(array('result' => false, 'message' => '这个二维码并非你负责！'));
//            exit;
//        }
//        //查看是否需要更新经纬度
//        $map = array('equ_id'=>$qrcode->equ_id);
//        $equipment = M('equipment')->where($map)->find();
//        if((!empty($equipment)) && (empty($equipment['logitude']) || empty($equipment['latitude']) || $equipment['locking']==1)){
//            $equipment1['logitude'] = $securityData->logitude;
//            $equipment1['latitude'] = $securityData->latitude;
//            $equipment1['locking'] = 0;
//            $equipment1['place_update_time'] = getTime();
//            M('equipment')->where($map)->save($equipment1);
//        }
          //如果是管理员更新经纬度
        $map = array('equ_id'=>$qrcode->equ_id);
        $equi = M('user')->where("userAccount='%s'",$token)->getField("identity");
        if($equi == 1){
            $equipment1['logitude'] = $securityData->logitude;
            $equipment1['latitude'] = $securityData->latitude;
            $equipment1['locking'] = 0;
            $equipment1['place_update_time'] = getTime();
            M('equipment')->where($map)->save($equipment1);
        }
        $equipment = M('equipment')->where($map)->find();
        //判断距离
        $distance = sphere_distance($equipment['latitude'], $equipment['logitude'], $securityData->latitude, $securityData->logitude);

        // 获取设置的范围
        $distance2 = M("setting")->where(array("key"=>'distance'))->getField('value');
        if($distance2 < $distance){
            echo json_encode(array('result' => false, 'message' => '还未到达指定地点，不能签到！'));
            exit;
        }
        $securityData->equipment = $qrcode->equ_id;
        $securityData->userAccount = $token;
        $securityData->ms = getTime();
        $model = M('sign');
        $result = $model->create($securityData);
        if (!$result) {
            echo json_encode(array('result' => false, 'message' => '创建数据失败'));
            exit;
        }
        if ($model->add()) {
            $ret = M('equipment')->field('equ_id,name,place,useraccount')->where($qrcode)->find();
            $ret['result'] = true;
            $ret['message'] = "success";
            echo json_encode($ret);
        } else {
            echo json_encode(array('result' => false, 'message' => '插入数据失败'));
        }
    }

}
